package main

import (
	"io"
	"log"
	"math/rand"
	"net/http"
	"time"

	"github.com/SkyAPM/go2sky"
	tracerestful "github.com/SkyAPM/go2sky-plugins/go-restful"
	"github.com/SkyAPM/go2sky/reporter"
	"github.com/emicklei/go-restful/v3"
)

func main() {
	ws := new(restful.WebService)
	ws.Filter(tracerestful.NewTraceFilterFunction(initTracer2()))
	ws.Route(ws.GET("/hello").To(hello2Handler))
	ws.Route(ws.GET("/bye").To(bye2Handler))
	restful.Add(ws)

	http.ListenAndServe("0.0.0.0:18081", nil)
}

func initTracer2() *go2sky.Tracer {
	re, err := reporter.NewGRPCReporter("localhost:11800")
	if err != nil {
		log.Fatalf("new reporter error %v \n", err)
	}
	tracer, err := go2sky.NewTracer("demo-service-beta", go2sky.WithReporter(re), go2sky.WithInstance(IPV4()))
	if err != nil {
		log.Fatalf("create tracer error %v \n", err)
	}
	return tracer
}

func hello2Handler(req *restful.Request, resp *restful.Response) {
	time.Sleep(time.Duration(80+rand.Intn(20)) * time.Millisecond)
	io.WriteString(resp, "hello. i am demo-service-beta")
}

func bye2Handler(req *restful.Request, resp *restful.Response) {
	time.Sleep(time.Duration(80+rand.Intn(20)) * time.Millisecond)
	io.WriteString(resp, "bye.  i am demo-service-beta")
}
